package Java多线程和并发.Java并发线程基础;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @program: algorithm
 * @description: 不可取消的任务在退出前恢复中断
 * @author: 陈恩涛
 * @create: 2022-04-04 09:56
 **/
public class RecoverInterrupt {

    public static void main(String[] args) throws InterruptedException {

        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);
        CountDownLatch start = new CountDownLatch(1);
        new Thread(() -> {
            try {
                start.await();
                queue.put(2);
            } catch (InterruptedException e) {
                // ignore
            }
        }, "t1").start();

        Thread t2 = new Thread(() -> {
            System.out.println(getNextInteger(queue));
        }, "t2");

        t2.start();
        t2.interrupt();
        TimeUnit.SECONDS.sleep(5);
        start.countDown();

    }

    /**
     *
     * 执行过程：第一次阻塞队列take阻塞，main线程中断t2,抛出中断异常，
     * 进入catch，第二次阻塞队列take阻塞，知道queue中有值被获取
     *
     * @param queue
     * @return
     */
    public static Integer getNextInteger(BlockingQueue<Integer> queue) {
        boolean interrupted = false;
        try {
            while (true) {
                try {
                    return queue.take();
                } catch (InterruptedException e) {
                    interrupted = true;
                    System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().isInterrupted());
                }
            }
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
                System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().isInterrupted());
            }
        }
    }
}
